package com.gitee.ywj1352.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Collections;
import java.util.Properties;

/**
 * @author wenjie.yang on 2019/6/20.
 */
public class KafkaConsumerDemo extends Thread{

    private final KafkaConsumer<Integer,String> kafkaConsumer;

    public KafkaConsumerDemo(String topic,String groupId){
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092");
        //消费组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,groupId);
        //自动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"1000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.IntegerDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //从最早的消费
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"latest");
        this.kafkaConsumer = new KafkaConsumer(properties);
        kafkaConsumer.subscribe(Collections.singletonList(topic));
        //可以给消费者制定分区
//        TopicPartition topicPartition = new TopicPartition(topic, 0);
//        kafkaConsumer.assign(Arrays.asList(topicPartition));
    }


    @Override
    public void run() {
        while (true){
            ConsumerRecords<Integer, String> poll = kafkaConsumer.poll(1000);
            //获取分区
            poll.forEach(s->System.out.println(" partition: " + s.partition() +";msg receive:"+s.value() +" threadId: "+Thread.currentThread().getId()));
            kafkaConsumer.commitAsync();
        }
    }

    public static void main(String[] args) {
        new KafkaConsumerDemo("ywj","G1").start();
        new KafkaConsumerDemo("ywj","G1").start();
    }
}
